package org.midy.infrastructure;

import org.midy.infrastructure.tools.Logger;

import java.nio.channels.SelectableChannel;
import java.nio.channels.SelectionKey;

public interface EventHandler {
    Object handle(SelectionKey selectionKey);

    default ChannelEventHelper checkSelectKeyAndChannel(SelectionKey selectionKey) {
        SelectableChannel channel = selectionKey.channel();
        if (!channel.isOpen()) {
            selectionKey.cancel();
            Logger.warn("SocketChannel 连接已经关闭！");
            return null;
        }
        return ChannelEventHelper.attachment(selectionKey);
    }

    default void cancelSelectionKeyAndCloseChannel(ChannelEventHelper channelEventHelper) {
        channelEventHelper.close();
    }
}
